<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2017-12-13 03:39:35 apple $
*/
defined('BY_JYA') or exit('error');
$_RQ['op']=$_RQ['op']?$_RQ['op']:'image';
$types=array(
	'image'=>'图片',
	'audio'=>'音频',
	'video'=>'视频',
);
if($_RQ['op']=='image'){
	//搜索
	$params=array('nochoose'=>0);
	$params['uniacid']=$_SESSION['uniacid'];
	$params['type']='image';
	if(!empty($_RQ['title'])){
		$params['title like']='%'.trim($_RQ['title']).'%';
		$return['params']['title']=$_RQ['title'];
	}
	if(isset($_RQ['group_id']) && $_RQ['group_id']!=-10){
		$params['group_id']=intval($_RQ['group_id']);
		if(intval($_RQ['group_id'])==-2){
			$params['mid >=']=0;
		}
		$return['params']['group_id']=$_RQ['group_id'];
	}
	if(!isset($return['params']['group_id'])){
		$return['params']['group_id']=-10;
	}
	if($_RQ['group_id2']){
		$params['group_id2']=intval($_RQ['group_id2']);
	}
	$return['params']['group_id2']=intval($_RQ['group_id2']);
	$fields=array('title','attachment','id','group_id','group_id2');
	$pindex = max(1, intval($_RQ['page']));
	$psize = 21;
	$total='';
	$list=pdo_getslice('core_attachment',$params,array($pindex,$psize),$total,$fields,'','id desc');
	foreach($list as &$row){
		if(!$row['title']){
			$row['title']='未设置标题';
		}
	}
	$return['groups']=pdo_getall('core_attachment_group',array('uniacid'=>$_SESSION['uniacid'],'pid'=>0),array('id','title'));
	if($return['groups']){
		foreach($return['groups'] as &$group){
			$group['num']=pdo_count('core_attachment',array('uniacid'=>$_SESSION['uniacid'],'type'=>'image','group_id'=>$group['id']));
		}
	}else{
		$return['groups']=array();
	}
	$no_group=array('id'=>0,'title'=>'未分组');
	$no_group['num']=pdo_count('core_attachment',array('uniacid'=>$_SESSION['uniacid'],'type'=>'image','group_id'=>0,'nochoose'=>0));
	array_unshift($return['groups'],$no_group);
	$manage=array('id'=>-1,'title'=>'系统图片');
	$manage['num']=pdo_count('core_attachment',array('uniacid'=>$_SESSION['uniacid'],'type'=>'image','group_id'=>-1,'nochoose'=>0));
	array_unshift($return['groups'],$manage);
	$custom=array('id'=>-2,'title'=>'用户图片');
	$custom['num']=pdo_count('core_attachment',array('uniacid'=>$_SESSION['uniacid'],'type'=>'image','group_id'=>-2,'nochoose'=>0,'mid >='=>0));
	array_unshift($return['groups'],$custom);
	$all=array('id'=>-10,'title'=>'全部图片');
	$all['num']=pdo_count('core_attachment',array('uniacid'=>$_SESSION['uniacid'],'type'=>'image','nochoose'=>0));
	array_unshift($return['groups'],$all);
	$return['list']=$list?$list:array();
	$totalpage=ceil($total/$psize);
	$totalpage=intval($totalpage);
	$return['total']=$total;
	$return['totalpage'] =$totalpage;
	$return['params']['page'] =$pindex;
	$group_id=$params['group_id'];
	if($params['group_id']>-3 && $params['group_id']){
		if($params['group_id']>0){
			$return['groupitem']=pdo_get('core_attachment_group',array('uniacid'=>$_SESSION['uniacid'],'id'=>$params['group_id']));
			$group_id=$return['groupitem']['pid']?:$group_id;
		}
		$return['pgroups']=pdo_getall('core_attachment_group',array('uniacid'=>$_SESSION['uniacid'],'pid'=>$group_id));
	}
	$return['pgroup_id']=$group_id;
	exi($return);
}
if($_RQ['op']=='audio'){
	//搜索
	$params=array();
	$params['uniacid']=$_SESSION['uniacid'];
	$params['type']='audio';
	if(!empty($_RQ['title'])){
		$params['title like']='%'.trim($_RQ['title']).'%';
		$return['params']['title']=$_RQ['title'];
	}
	$fields=array('title','attachment','id','createtime');
	$pindex = max(1, intval($_RQ['page']));
	$psize = 21;
	$total='';
	$list=pdo_getslice('core_attachment',$params,array($pindex,$psize),$total,$fields,'','id desc');
	foreach($list as &$row){
		$row['createtime']=date('Y-m-d H:i',$row['createtime']);
		if(!$row['title']){
			$row['title']='未设置标题';
		}
	}
	$return['list']=$list?$list:array();
	$totalpage=ceil($total/$psize);
	$totalpage=intval($totalpage);
	$return['totalpage'] =$totalpage;
	$return['params']['page'] =$pindex;
	exi($return);
}
if($_RQ['op']=='video'){
	//搜索
	$params=array();
	$params['uniacid']=$_SESSION['uniacid'];
	$params['type']='video';
	if(!empty($_RQ['title'])){
		$params['title like']='%'.trim($_RQ['title']).'%';
		$return['params']['title']=$_RQ['title'];
	}
	$fields=array('title','attachment','id');
	$pindex = max(1, intval($_RQ['page']));
	$psize = 21;
	$total='';
	$list=pdo_getslice('core_attachment',$params,array($pindex,$psize),$total,$fields,'','id desc');
	foreach($list as &$row){
		if(!$row['title']){
			$row['title']='未设置标题';
		}
	}
	$return['list']=$list?$list:array();
	$totalpage=ceil($total/$psize);
	$totalpage=intval($totalpage);
	$return['totalpage'] =$totalpage;
	$return['params']['page'] =$pindex;
	exi($return);
}
if($_RQ['op']=='add'){
	$return=array('item'=>array('type'=>'image','uptype'=>0));
	$imagesdemo=SITEROOT.'core/resource/imagesdemo.zip';
	$diyfile=ROOT_AT.'oss/'.$_SESSION['uniacid'].'/diy/';
	cfc('files')->mkdirs($diyfile);
	$return['htmls']=array(
		'type'=>'edit',
		'post'=>'post',
		'tabs'=>array(
			array('op'=>'image','title'=>'返回附件列表'),
			array('op'=>'add','title'=>'批量上传附件'),
		),
		'edit'=>array(
			array('type'=>'tip','title'=>'【温馨提示】：库里已存在的图片源，是不能二次上传的！所以可能部分图片会上传不成功！'),
			array('type'=>'radio','name'=>'uptype','title'=>'上传方式','options'=>'uptypes','help'=>''),
			array('type'=>'radio','name'=>'type','title'=>'上传附件类型','options'=>'types','help'=>'上传时，系统会自动忽略文件格式不合法的文件'),
			array('type'=>'upfile','name'=>'files','title'=>'上传附件压缩包','show'=>array('uptype'=>1),'help'=>'请上传zip格式压缩包。 <a href="'.$imagesdemo.'">【下载示例压缩包】</a> 上传前可以先对图片进行分组，放到普通文件夹，系统将自动识别文件夹并将图片存放到相应附件分组下（文件夹目录不要是中文的）！'),
			/*array('type'=>'select2_line','name'=>'groupid','options'=>'groups','title'=>'选择附件分组',
					'name2'=>'group2id','options2'=>'groups2','title2'=>'选择附件子分组',
			),*/
			array('type'=>'tip','title'=>'【批量上传】：点击上传，然后选择主分组和子分组，上传的图片就会到指定的分组里面去！','show'=>array('uptype'=>0)),
			array('type'=>'images','name'=>'images','title'=>'批量上传附件','show'=>array('uptype'=>0),'help'=>''),
		),
	);
	$return['types']=$types;
	$return['groups']=$newgroups;
	$return['groups']=pdo_getall('core_attachment_group',array('uniacid'=>$_SESSION['uniacid'],'pid'=>0),array('id','title'),'id');
	foreach($return['groups'] as &$pv){
		$pv['groups2']=pdo_getall('core_attachment_group',array('uniacid'=>$_SESSION['uniacid'],'pid'=>$pv['id']),array('title','id'),'id');
	}
	$return['uptypes']=array('批量上传','按附件包上传');
	exi($return);
}
if($_RQ['op']=='post'){
	$postdata=get_postdata();
	$uptype=$postdata['uptype'];
	$type=$postdata['type'];
	if($uptype && (!$types[$type] || !$postdata['files'])){
		exi('请先选择要上传的附件类型和附件压缩包！','error');
	}
	if(!$uptype){
		exi('无需提交，点击《批量上传附件》即可！','error');
	}
	$setting=core_setting('upload');
	$yes=str_array($setting[$type.'_ext']);
	foreach($yes as &$ye){
		$ye='.'.$ye;
	}
	$file=cfc('files')->local($postdata['files']);
	$temp=ROOT_AT.'temp/'.random(30);
	$zip=new ZipArchive();
	$zip->open($file);
	$zip->extractTo($temp);
	$files=cfc('files')->file_tree($temp,array(),$yes);
	$diyfile='oss/'.$_SESSION['uniacid'].'/diy/';
	if(!$uptype){
		cfc('files')->mkdirs(ROOT_AT.$diyfile.$postdata['groupname'].'/');
	}
	foreach($files as $row){		
		$file_array=explode("/",$row,3);	
		if(count($file_array)==2){
			$filetitle=$file_array[1];
			$dir='';
		}else{
			$filetitle=$file_array[2];
			$dir=$file_array[1];
		}
		$index=strpos($filetitle,'.');
		$ext=substr($filetitle,$index+1);
		$filetitle=substr($filetitle,0,$index);
		if(!$uptype){
			$dir=$postdata['groupname'];
		}
		if($dir){
			$dir=iconv('gbk',"utf-8//IGNORE",$dir);
			$group_id=pdo_getcolumn('core_attachment_group',array('uniacid'=>$_SESSION['uniacid'],'title'=>$dir),'id');
			if(!$group_id){
				$insert=array(
					'uniacid'=>$_SESSION['uniacid'],
					'title'=>$dir,
				);
				pdo_insert('core_attachment_group',$insert);
				$group_id=pdo_insertid();
			}
			$filenameurl=$diyfile.$dir.'/';
			if($uptype && !$ismk[$dir]){
				cfc('files')->mkdirs(ROOT_AT.$diyfile.$dir.'/');
				$ismk[$dir]=true;
			}
		}else{
			$group_id=0;
			$filenameurl=$diyfile.$type.'s/';
		}
		//$filetitle=iconv('gbk',"utf-8//IGNORE",$filetitle);
		do {
			$filename = random(10) . '.' . $ext;
		} while (file_exists(ROOT_AT .$filenameurl.$filename));
		$filenameurl .=$filename;
		//print_r($filenameurl);exit;
		cfc('files')->source_save($temp.$row,$type,$ext,$filetitle,$filenameurl,$group_id);
	}
	cfc('files')->rmdirs($temp);
	exi('批量增加附件成功！','','image');
}
if($_RQ['op']=='ctitle'){
	if($_RQ['postdata']){
		$postdata=get_postdata();
		$id=intval($postdata['id']);
		if(!$id){
			exi('请先选择附件1！','error');
		}
		$postdata=get_postdata();
		$filename=trim($postdata['title']);
		if($filename){
			pdo_update('core_attachment',array('title'=>$filename),array('id'=>$id,'uniacid'=>$_SESSION['uniacid']));
		}
		exi('附件名称修改成功！');
	}
	$id=intval($_RQ['id']);
	if(!$id){
		exi('请先选择附件2！','error');
	}
	$return=array();
	$return['item']=pdo_get('core_attachment',array('id'=>$id,'uniacid'=>$_SESSION['uniacid']),array('id','title'));
	$return['htmls']=array(
		'type'=>'edit',
		'desc'=>'修改附件名称',
		'edit'=>array(
			array('type'=>'string','name'=>'title','title'=>'附件名称'),
		),
	);
	exi($return);
}
if($_RQ['op']=='cgroup'){
	if($_RQ['postdata']){
		$postdata=get_postdata();
		$id=intval($postdata['id']);
		$ids=trim($postdata['ids']);
		if(!$id && !$ids){
			exi('请先选择附件！','error');
		}
		if($ids){
			$ids=trim($ids,';');
			if($ids){
				$ids=explode(';',$ids);
			}
		}
		if(!$ids){
			$ids=array();
		}
		if($id){
			$ids[]=$id;
		}
		$group_id=intval($postdata['group_id']);
		if($group_id){
			foreach($ids as $id){
				$id=intval($id);
				if($id){
					pdo_update('core_attachment',array('group_id'=>$group_id),array('id'=>$id,'uniacid'=>$_SESSION['uniacid']));
				}
			}
		}
		exi('附件分组修改成功！');
	}
	$id=intval($_RQ['id']);
	$ids=trim($_RQ['ids']);
	if(!$id && !$ids){
		exi('请先选择附件！','error');
	}
	$return=array();
	$return['item']=array('id'=>$id,'ids'=>$ids);
	$return['groups']=pdo_getall('core_attachment_group',array('uniacid'=>$_SESSION['uniacid']),array('id','title'));
	$return['groups'][]=array(
		'id'=>-1,
		'title'=>'系统图片',
	);
	$return['groups'][]=array(
		'id'=>-2,
		'title'=>'用户图片',
	);
	$return['htmls']=array(
		'type'=>'edit',
		'desc'=>'移动附件分组',
		'edit'=>array(
			array('type'=>'select','name'=>'group_id','title'=>'所属分组','options'=>'groups'),
		),
	);
	exi($return);
}
if($_RQ['op']=='list2'){
	$pindex = max(1, intval($_RQ['page']));
	$psize = 10;
	$params=array('uniacid'=>$_SESSION['uniacid']);
	$params['pid']=intval($_RQ['id'])?:intval($_RQ['pid']);
	$return['params']['pid'] = $params['pid'];
	if(!empty($_RQ['title'])){
		$params['title like']='%'.trim($_RQ['title']).'%';
		$return['params']['title']=$_RQ['title'];
	}
	$parenttitle=pdo_getcolumn('core_attachment_group',array('id'=>$params['pid']),'title');
	$parenttitle=$parenttitle?:'';
    $orderby='id desc';
	$total='';
	$return['list']=pdo_getslice('core_attachment_group',$params,array($pindex,$psize),$total,$fields,'',$orderby);
	$totalpage=ceil($total/$psize);
	$totalpage=intval($totalpage);
	$return['totalpage'] =$totalpage;
	$return['params']['page'] =$pindex;
	$htmls=array(
		'type'=>'list',
		'tabs'=>array(
			array('op'=>'list2','title'=>$parenttitle.'子分组'),
			array('op'=>'edit2','title'=>'添加子分组','query'=>'pid='.$params['pid']),
		),
		'list'=>array('data'=>'list','tip'=>'','edit'=>false,'list'=>array(			
			array('name'=>'title','title'=>'子分组名称','type'=>'string'),	
		),'action'=>array(
			array('type'=>'href','op'=>'edit2','title'=>'编辑'),
		)
		),
	);
	$return['htmls']=$htmls;
	exi($return);
}
if($_RQ['op']=='edit2'){
	if($_RQ['postdata']){
		$postdata=get_postdata();
		$title=trim($postdata['title']);
		$id=$postdata['id'];
		if($id){
			pdo_update('core_attachment_group',array('title'=>$title),array('id'=>$id,'uniacid'=>$_SESSION['uniacid']));
			exi('分组修改成功！','','goback');
		}else{
			$insert=array(
				'uniacid'=>$_SESSION['uniacid'],
				'pid'=>$postdata['pid'],
				'title'=>$title,
			);
			pdo_insert('core_attachment_group',$insert);
			exi('分组添加成功！','','goback');
		}
	}
	$id=intval($_RQ['id']);
	if($id){
		$item=pdo_get('core_attachment_group',array('id'=>$id));
	}else{
		$item=array();
		if($_RQ['pid']){
			$item['pid']=intval($_RQ['pid']);
			$item['parenttitle']=pdo_getcolumn('core_attachment_group',array('id'=>$item['pid']),'title');
		}else{
			exi('请选择主分组添加子分组！','error');
		}
	}
	$item['shifeeset']=json_decode($item['shifeeset'],true);
	$item['feeset']=json_decode($item['feeset'],true);
    $return['item']=$item;	
	$htmls=array(
		'type'=>'edit',
		'desc'=>'子分组编辑',
		'tabs'=>array(
			array('op'=>'list2','title'=>$item['parenttitle'].'子分组'),
		),
		'edit'=>array(
			array('name'=>'title','title'=>'子分组名称','type'=>'string'),		
		)
	);
	$return['htmls']=$htmls;
	exi($return);
}
if($_RQ['op']=='add_group'){
	$id=intval($_RQ['id']);
	if($_RQ['postdata']){
		$postdata=get_postdata();
		$cs=var_export($postdata,true);
		//exi($cs,'error');
		$title=trim($postdata['title']);
		$id=$postdata['id'];
		if($id){
			pdo_update('core_attachment_group',array('title'=>$title),array('id'=>$id,'uniacid'=>$_SESSION['uniacid']));
			exi('分组修改成功！','','goback');
		}else{
			$insert=array(
				'uniacid'=>$_SESSION['uniacid'],
				'title'=>$title,
			);
			pdo_insert('core_attachment_group',$insert);
			exi('分组添加成功！','','goback');
		}
	}
	if($id){
		$item=pdo_get('core_attachment_group',array('id'=>$id,'uniacid'=>$_SESSION['uniacid']),array('id','title'));
	}else{
		$item=array();
	}
	$return=array('item'=>$item);
	$return['htmls']=array(
		'type'=>'edit',
		'edit'=>array(
			array('type'=>'string','name'=>'title','title'=>'分组名称'),
		),
	);
	if($id){
		$return['htmls']['desc']='编辑分组';
	}else{
		$return['htmls']['desc']='新增分组';
	}
	exi($return);
}
if($_RQ['op'] == 'delgroup'){
	$id=intval($_RQ['id']);
	if($id){
		$isadd=pdo_count('core_attachment',array('group_id'=>$id,'uniacid'=>$_SESSION['uniacid']));
		if($isadd){
			exi('该分组下面还有图片，请先移除！','error');
		}
		pdo_delete('core_attachment_group',array('id'=>$id,'uniacid'=>$_SESSION['uniacid']));
		exi('删除成功！','','goback');
	}else{
		exi('请选择分组！','error');
	}
}
if($_RQ['op'] == 'del'){
	$id=intval($_RQ['id']);
	if($id){
		cfc('files')->source_del($id);
		exi('附件删除成功！');
	}
	$del=trim($_RQ['del'],';');
	if($del){
		$del=explode(';',$del);
		foreach($del as $id){
			$id=intval($id);
			if($id){
				cfc('files')->source_del($id);
			}
		}
	}
	exi('附件删除成功！');
}
if($_RQ['op'] == 'clear'){
	//清理附件
	$num=pdo_count('core_attachment',array('uniacid'=>$_SESSION['uniacid']));
	$pages=intval(ceil($num/1000));
	$dels=array();
	for($i=1;$i<=$pages;$i++){
		$list=pdo_getslice('core_attachment',array('uniacid'=>$_SESSION['uniacid']),array($i,1000),$total,array('id','attachment'));
		if($list){
			foreach($list as $item){
				if(!ATTACHMENT_TYPE){
					if(!is_file(ROOT_AT.$item['attachment'])){
						$dels[]=$item['id'];
					}
				}else{
					$check=get_headers(tomedia($item['attachment']),true);
					
				}
			}
		}
	}
	if($dels){
		pdo_delete('core_attachment',array('id'=>$dels));
	}
	exi('清理成功！');
}
if($_RQ['op'] == 'cleargoods'){
	//清理附件
	$num=pdo_count('core_attachment',array('uniacid'=>$_SESSION['uniacid']));
	$pages=intval(ceil($num/1000));
	$dels=array();
	for($i=1;$i<=$pages;$i++){
		$list=pdo_getslice('core_attachment',array('uniacid'=>$_SESSION['uniacid']),array($i,1000),$total,array('id','attachment'));
		if($list){
			foreach($list as $item){
				if(!ATTACHMENT_TYPE){
					if(!is_file(ROOT_AT.$item['attachment'])){
						$dels[]=$item['id'];
					}
				}else{
					$check=get_headers(tomedia($item['attachment']),true);
					
				}
			}
		}
	}
	if($dels){
		pdo_delete('core_attachment',array('id'=>$dels));
	}
	exi('清理成功！');
}
function addfujian($src,$type){
	global $_AR;
	$dir = opendir($src);
    while(false !== ( $file = readdir($dir)) ) {
        if (( $file != '.' ) && ( $file != '..' )) {
            if ( is_dir($src . '/' . $file) ) {
                addfujian($src . '/' . $file);
            }
            else {
				$filen=iconv('EUC-CN',"utf-8//IGNORE",$file);
				$temp=strrchr($file,'.');
				$title=str_replace($temp,'',$filen);
				$ext=strtolower(substr($temp,1));
				$setting=core_setting('upload');
				$yes=trim($setting[$type.'_ext'],';');
				$yes=explode(';',$yes);
				if(in_array($ext,$yes)){
					cfc('files')->source_save($src . '/' . $file,$type,$ext,$title);
				}
            }
        }
    }
    closedir($dir);
}
